package com.zdkj.subway.st.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.core.util.SpringContextHolder;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.constant.enums.StockEnum;
import com.zdkj.subway.st.entity.*;
import com.zdkj.subway.st.mapper.SwStTicketHandMapper;
import com.zdkj.subway.st.service.SwStTicketHandDetailService;
import com.zdkj.subway.st.service.SwStTicketHandService;
import com.zdkj.subway.st.util.DateUtilsSt;
import com.zdkj.subway.st.util.GenSerialNo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;


/**
 * 车票上交主表
 *
 * @author cuilei
 * @date 2020-05-26 15:03:29
 */
@Service
@AllArgsConstructor
public class SwStTicketHandServiceImpl extends ServiceImpl<SwStTicketHandMapper, SwStTicketHand> implements SwStTicketHandService {
    private final SwStInputDetailServiceImpl swStInputDetailService;
    private final SwStOutputDetailServiceImpl swStOutputDetailService;
    private final SwStTicketHandDetailService swStTicketHandDetailService;
    @Autowired
    private SwStStockDayCheckDetailServiceImpl sdcd;
    @Autowired
    private GenSerialNo genSerialNo;
    @Resource
    SwStInputDetailServiceImpl inputDetailServiceImpl;
    @Resource
    SwStOutputDetailServiceImpl outputDetailServiceImpl;
    private int getInputSettleNum(SwStInputDetail swStInputDetail) {
        int settleNum = 0;
        int outStorageNum = sdcd.getOutStorgeNum(swStInputDetail.getTicketType(), swStInputDetail.getStockArea());
        int inStorageNum = sdcd.getInStorgeNum(swStInputDetail.getTicketType(), swStInputDetail.getStockArea());
        if (outStorageNum == 0 && inStorageNum == 0) {
            settleNum = 0;
        } else if (outStorageNum == 0 && inStorageNum != 0) {
            settleNum = inStorageNum;
        } else {
            //统计最新库存量 如果尚未尚未出库过，则库存为入库数
            settleNum = sdcd.getSettleNum(swStInputDetail.getTicketType(), swStInputDetail.getStockArea());
        }
        return settleNum;
    }
    @Transactional(rollbackFor = Exception.class)
    public boolean saveInputDetail(SwStInputDetail swStInputDetail) {
        boolean issuccuess = true;
        //首先更新库存账
        SwStStockDayCheckDetail swStStockDayCheckDetail = new SwStStockDayCheckDetail();
        try {
            //统计最新库存量 如果尚未尚未出库过，则库存为入库数
            int settleNum = this.getInputSettleNum(swStInputDetail);
            //设置票种
            swStStockDayCheckDetail.setTicketType(swStInputDetail.getTicketType());
            //车票名称
            swStStockDayCheckDetail.setTicketName(swStInputDetail.getTicketName());
            //车票次数
            swStStockDayCheckDetail.setTicketTimes(swStInputDetail.getTicketTimes());
            //车票金额
            swStStockDayCheckDetail.setTicketPrice(swStInputDetail.getTicketPrice());
            //出入库类型
            swStStockDayCheckDetail.setStorageType("入库");
            //出入库票价
            swStStockDayCheckDetail.setTicketPrice(swStInputDetail.getTicketPrice());
            //设置库存分区
            swStStockDayCheckDetail.setStockArea(swStInputDetail.getStockArea());
            //更新库存量
            swStStockDayCheckDetail.setStorageNumber(swStInputDetail.getTicketNumber());
            //更新结存量=最新库存量+当前出库
            swStStockDayCheckDetail.setSettleNumber(settleNum + swStInputDetail.getTicketNumber());
            issuccuess = sdcd.save(swStStockDayCheckDetail);
            if (!issuccuess) {
                issuccuess = false;
                throw new RuntimeException("库存更新异常！");
            }
            //其次更新入库基础表
            PigxUser user = SecurityUtils.getUser();
            swStInputDetail.setCreatorName(user.getUsername());
            swStInputDetail.setCreatorId(user.getId());
            //设置关联库存id
            swStInputDetail.setStockdayid(swStStockDayCheckDetail.getId());
            //未分解
            swStInputDetail.setBreakFlag("0");
            //其他关联方式入库，不需要重新设置流水号
            if (StringUtils.isEmpty(swStInputDetail.getInstockno())) {
                //根据票种生成单号前缀
                String prefix = genSerialNo.getPreFixByTicketType(swStInputDetail.getTicketType());
                String serialno = genSerialNo.genSerioNo(StockEnum.StockType.INSTOCK.getValue());
                swStInputDetail.setInstockno(prefix+serialno);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return issuccuess && swStInputDetailService.save(swStInputDetail);
    }

    @Override
    public boolean inputDetailSubmitBatch(List<Integer> ids){
        PigxUser user = SecurityUtils.getUser();
        Collection<SwStTicketHand> swStTicketHandlist = listByIds(ids);
        List<SwStInputDetail> list = new ArrayList<>();
        boolean isSucss = true;
        for(SwStTicketHand item :swStTicketHandlist){
			item.setIsInstock("1");
            Collection<SwStTicketHandDetail> swTkTicketDeliveryDetailList  = swStTicketHandDetailService.list(Wrappers.<SwStTicketHandDetail>query().lambda().eq(SwStTicketHandDetail::getRefId, item.getId()));
            for(SwStTicketHandDetail detail :swTkTicketDeliveryDetailList){
                SwStInputDetail swStInputDetail = new SwStInputDetail();
                swStInputDetail.setInGoingType("6");
                swStInputDetail.setInGoingTime(DateUtilsSt.newLocalDateTime());
                swStInputDetail.setKeepercode(item.getReceivePersonCode());
                swStInputDetail.setKeepername(item.getReceivePersonName());
                swStInputDetail.setTicketType(detail.getTicketType());
                swStInputDetail.setTicketName(detail.getTicketName());
                swStInputDetail.setTicketTimes(Objects.equals(detail.getTicketCount(), "") || detail.getTicketCount() == null ? 0 : Integer.parseInt(detail.getTicketCount()));
                swStInputDetail.setTicketPrice(detail.getTicketAmount());
                swStInputDetail.setTicketNumber(detail.getRealReceiveCount());
                swStInputDetail.setActiveTime(Optional.ofNullable(detail.getCardNumber()).orElse("0"));
                swStInputDetail.setTicketNo(detail.getNumberInterval());
                swStInputDetail.setKeeper1code(user.getUserCode());
                swStInputDetail.setKeeper1name(user.getNikeName());
                swStInputDetail.setRemark(detail.getRemark());
                swStInputDetail.setDataSource("3");//数据来源：3：回收
                //入库生成单号和更新基础表信息
                inputDetailServiceImpl.inputGenerateSingle(swStInputDetail);
                list.add(swStInputDetail);
                //isSucss =swStInputDetailService.save(swStInputDetail);
            }

        }
        //用于更新是否操作入库
        updateBatchById(swStTicketHandlist);
        return swStInputDetailService.saveBatch(list);
    }

    @Override
    public boolean inputDetailSubmitNew(List<Integer> ids) {
        PigxUser user = SecurityUtils.getUser();
        Collection<SwStTicketHand> swStTicketHandlist = listByIds(ids);
        List<SwStInputDetail> list = new ArrayList<>();
        boolean isSucss = true;
        for(SwStTicketHand item :swStTicketHandlist){
            item.setIsInstock("1");
            Collection<SwStTicketHandDetail> swTkTicketDeliveryDetailList  = swStTicketHandDetailService.list(Wrappers.<SwStTicketHandDetail>query().lambda().eq(SwStTicketHandDetail::getRefId, item.getId()));
            for(SwStTicketHandDetail detail :swTkTicketDeliveryDetailList){
                SwStInputDetail swStInputDetail = new SwStInputDetail();
                swStInputDetail.setInGoingType("6");
                swStInputDetail.setInGoingTime(DateUtilsSt.newLocalDateTime());
                swStInputDetail.setKeepercode(item.getReceivePersonCode());
                swStInputDetail.setKeepername(item.getReceivePersonName());
                swStInputDetail.setTicketType(detail.getTicketType());
                swStInputDetail.setTicketName(detail.getTicketName());
                swStInputDetail.setTicketTimes(Objects.equals(detail.getTicketCount(), "") || detail.getTicketCount() == null ? 0 : Integer.parseInt(detail.getTicketCount()));
                swStInputDetail.setTicketPrice(detail.getTicketAmount());
                swStInputDetail.setTicketNumber(detail.getRealReceiveCount());
                swStInputDetail.setActiveTime(Optional.ofNullable(detail.getCardNumber()).orElse("0"));
                swStInputDetail.setTicketNo(detail.getNumberInterval());
                swStInputDetail.setKeeper1code(user.getUserCode());
                swStInputDetail.setKeeper1name(user.getNikeName());
                swStInputDetail.setRemark(detail.getRemark());
                swStInputDetail.setDataSource("3");//数据来源：3：回收
                swStInputDetail.setTicketReturnType(detail.getTicketReturnType());
				String ticketType = detail.getTicketType();
				//非单程票和营销车票不做入库
				if(!("DCP".equals(ticketType) || "YXCP".equals(ticketType))){
					continue;
				}
				swStInputDetail.setStockAreaTemorary("11");  //暂存区
				/* 20250417统一改为放到暂存区
				String ticketName = detail.getTicketName();
				if("PTDCP".equals(ticketName)){
					if (!StringUtils.isEmpty(detail.getTicketReturnType()) && "10".equals(detail.getTicketReturnType())) { //即时替换
						continue;

					}else{
						swStInputDetail.setStockAreaTemorary("8");  //待清洗区
					}
				}else {
					if("RECYCLEYXCP".equals(ticketName)){
						swStInputDetail.setStockAreaTemorary("10");  //待销毁区
					}else{
						swStInputDetail.setStockAreaTemorary("11");  //暂存区
					}
				}
				*/

               
                /*
                if (!StringUtils.isEmpty(detail.getTicketReturnType())) {
                    if ("6".equals(detail.getTicketReturnType()) || "7".equals(detail.getTicketReturnType())) { //AGM回收票  单程票退票
                        swStInputDetail.setStockAreaTemorary("8");  //待清洗区
                    } else if ("8".equals(detail.getTicketReturnType())) { //单程票无效票
                        swStInputDetail.setStockAreaTemorary("10");  //待销毁区
                    } else {
                        swStInputDetail.setStockAreaTemorary("10");
                    }
                }
				 if (!"PTDCP".equals(detail.getTicketName())) {
                    continue;
                }
                //根据 车票上交回收类型 设置 库存分区
				 if (!StringUtils.isEmpty(detail.getTicketReturnType())) {
					if ("10".equals(detail.getTicketReturnType())) { //即时替换
						continue;

					}else{
						swStInputDetail.setStockAreaTemorary("8");  //待清洗区
					}

				 }

				    1	TVM废票
					2	BOM废票
					3	AGM废票
					4	STM废票
					5	车票回收箱废票
					6	AGM回收票
					7	单程票退票
					8	单程票无效票
					9	人工回收单程票
					10	即时替换

					1	656
					2	647
					4	289
					5	1397
					6	24276
				*/
                //入库生成单号和更新基础表信息
                inputDetailServiceImpl.inputGenerateSingle(swStInputDetail);
                list.add(swStInputDetail);
                //isSucss =swStInputDetailService.save(swStInputDetail);
            }

        }
        //用于更新是否操作入库
        updateBatchById(swStTicketHandlist);
        return swStInputDetailService.saveBatch(list);
    }

    private int getOutputSettleNum(SwStOutputDetail swStOutputDetail) {
        int settleNum = 0;
        int outStorageNum = sdcd.getOutStorgeNum(swStOutputDetail.getTicketType(), swStOutputDetail.getStockArea());
        int inStorageNum = sdcd.getInStorgeNum(swStOutputDetail.getTicketType(), swStOutputDetail.getStockArea());
        if (outStorageNum == 0 && inStorageNum == 0) {
            settleNum = 0;
        } else if (outStorageNum == 0 && inStorageNum != 0) {
            settleNum = inStorageNum;
        } else {
            //统计最新库存量 如果尚未尚未出库过，则库存为入库数
            settleNum = sdcd.getSettleNum(swStOutputDetail.getTicketType(), swStOutputDetail.getStockArea());
        }
        return settleNum;
    }
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOutputDetail(SwStOutputDetail swStOutputDetail) {
        boolean issuccuess = true;
        //首先更新库存账
        SwStStockDayCheckDetail swStStockDayCheckDetail = new SwStStockDayCheckDetail();
        try {
            //统计最新库存量
            int settleNum = this.getOutputSettleNum(swStOutputDetail);
            //设置票种
            swStStockDayCheckDetail.setTicketType(swStOutputDetail.getTicketType());
            //车票名称
            swStStockDayCheckDetail.setTicketName(swStOutputDetail.getTicketName());
            //车票次数
            swStStockDayCheckDetail.setTicketTimes(swStOutputDetail.getTicketTimes());
            //车票金额
            swStStockDayCheckDetail.setTicketPrice(swStOutputDetail.getTicketPrice());
            //设置流动后库存
            swStStockDayCheckDetail.setStockArea(swStOutputDetail.getStockArea());
            //设置出库类型
            swStStockDayCheckDetail.setStorageType("出库");
            //更新库存量
            swStStockDayCheckDetail.setStorageNumber(swStOutputDetail.getTicketNumber());
            //更新结存量=最新库存量-当前出库
            swStStockDayCheckDetail.setSettleNumber(settleNum - swStOutputDetail.getTicketNumber());
            issuccuess = sdcd.save(swStStockDayCheckDetail);
            if (!issuccuess) {
                issuccuess = false;
                throw new RuntimeException("库存更新异常！");
            }
            //其次更新入库基础表
            PigxUser user = SecurityUtils.getUser();
            swStOutputDetail.setCreatorName(user.getUsername());
            swStOutputDetail.setCreatorId(user.getId());
            //设置关联库存id
            swStOutputDetail.setStockdayid(swStStockDayCheckDetail.getId());
            //所有出库信息默认为否
            swStOutputDetail.setIsreceive("否");
            //其他关联方式入库，不需要重新设置流水号
            if (StringUtils.isEmpty(swStOutputDetail.getOutstockno())) {
                //根据票种生成单号前缀
                String prefix = genSerialNo.getPreFixByTicketType(swStOutputDetail.getTicketType());
                String serialno = genSerialNo.genSerioNo(StockEnum.StockType.OUTSTOCK.getValue());
                swStOutputDetail.setOutstockno(prefix+serialno);
            }
            issuccuess = issuccuess && swStOutputDetailService.save(swStOutputDetail);
            SwTkOutStockReceive swTkOutStockReceive = SpringContextHolder.getBean(SwTkOutStockReceive.class);
            issuccuess = issuccuess && swTkOutStockReceive.saveTicketReceiveInfo(swStOutputDetail);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return issuccuess;
    }


    @Override
    public boolean outputDetailSubmitBatch(List<Integer> ids){
        PigxUser user = SecurityUtils.getUser();
        Collection<SwStTicketHand> swStTicketHandlist = listByIds(ids);
        List<SwStOutputDetail> list = new ArrayList<>();
        boolean isSucss = true;
        for(SwStTicketHand item :swStTicketHandlist){
			item.setIsOutstock("1");
            Collection<SwStTicketHandDetail> swTkTicketDeliveryDetailList  = swStTicketHandDetailService.list(Wrappers.<SwStTicketHandDetail>query().lambda().eq(SwStTicketHandDetail::getRefId, item.getId()));
            for(SwStTicketHandDetail detail :swTkTicketDeliveryDetailList){
                SwStOutputDetail swStOutputDetail = new SwStOutputDetail();
                swStOutputDetail.setOutGoingType("8");
                swStOutputDetail.setOutGoingTime(DateUtilsSt.newLocalDateTime());
                swStOutputDetail.setKeepercode(item.getReceivePersonCode());
                swStOutputDetail.setKeepername(item.getReceivePersonName());
                swStOutputDetail.setTicketType(detail.getTicketType());
                swStOutputDetail.setTicketName(detail.getTicketName());
                swStOutputDetail.setTicketTimes(Objects.equals(detail.getTicketCount(),"")||detail.getTicketCount()==null?0:Integer.parseInt(detail.getTicketCount()));
                swStOutputDetail.setTicketPrice(detail.getTicketAmount());
                swStOutputDetail.setTicketNumber(detail.getRealReceiveCount());
                swStOutputDetail.setActiveTime(Optional.ofNullable(detail.getCardNumber()).orElse("0"));
                swStOutputDetail.setTicketNo(detail.getNumberInterval());
                swStOutputDetail.setKeeper1code(user.getUserCode());
                swStOutputDetail.setKeeper1name(user.getNikeName());
                swStOutputDetail.setRemark(detail.getRemark());
                swStOutputDetail.setDataSource("3");//数据来源：3：回收
                //出库生成单号和更新基础表信息
                outputDetailServiceImpl.outputGenerateSingle(swStOutputDetail);
                list.add(swStOutputDetail);
                //isSucss = swStOutputDetailService.save(swStOutputDetail);
            }

        }
        //用于更新是否操作出库
        updateBatchById(swStTicketHandlist);
        return swStOutputDetailService.saveBatch(list);
    }
}
